package com.dazhi.boot.web.embedded.tomcat;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class TomcatServletWebServerFactory {
    public void getWebServer() throws LifecycleException, IOException {
        // 创建临时目录作为tomcat的基础目录
        Path tempBaseDir = Files.createTempDirectory("tomcat-temp-base-dir");
        // 创建临时目录作为应用文档资源的目录
        Path tempDocDir = Files.createTempDirectory("tomcat-temp-doc-dir");

        Tomcat tomcat = new Tomcat();
        // 配置连接器
        Connector connector = new Connector();
        // 设置绑定端口
        connector.setPort(8080);
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        tomcat.setBaseDir(tempBaseDir.toFile().getAbsolutePath());
        // 配置Container
        // 配置engine，管理多个虚拟站点
        // 配置host
        StandardContext context = (StandardContext) tomcat.addWebapp("/", (new File("res")).getAbsolutePath());
        context.setParentClassLoader(TomcatServletWebServerFactory.class.getClassLoader());
        context.setUseRelativeRedirects(false);
        // 加载localeMappings

//        context.addApplicationListener("org.springframework.web.context.ContextLoaderListener");

//        Wrapper wrapper = Tomcat.addServlet(context,"helloServlet", new HelloServlet());
//        wrapper.addMapping("/hello");


        tomcat.start();
        tomcat.getServer().await();
    }

    public static void start() throws LifecycleException, IOException {
        Tomcat tomcat = new Tomcat();
        String baseDir = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        tomcat.setBaseDir(baseDir);
        tomcat.setPort(8089);
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(8089);
        tomcat.setConnector(connector);

        tomcat.addWebapp("/", baseDir);
        tomcat.enableNaming();
        //手动创建
        //tomcat.getConnector();
        tomcat.start();
        tomcat.getServer().await();
    }


    public static void main(String[] args) {
        /*TomcatServletWebServerFactory t = new TomcatServletWebServerFactory();
        try {
            t.getWebServer();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/

        try {
            start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
